package cn.itsource.controller;

import cn.itsource.pojo.User;
import cn.itsource.pojo.bo.UserBO;
import cn.itsource.service.UserService;
import cn.itsource.utils.CookieUtils;
import cn.itsource.utils.JSONResult;
import cn.itsource.utils.JsonUtils;
import cn.itsource.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Api(value = "登录注册",tags = {"用于注册登录的相关接口"})
@RestController
@RequestMapping("passport")
public class PassPortController {

    @Autowired
    UserService userService;

    @ApiOperation(value = "用户名是否存在",notes = "用户是否存在",httpMethod = "GET")
    @GetMapping("/userNameIsExist")
    public JSONResult usernameIsExist(String username) {
        //1. 非空验证
        if(StringUtils.isBlank(username)){ // 空格、tab 键、换行符
            return JSONResult.errorMsg("用户名不能为空！");
        }

        //2. 是否存在
        boolean isExist = userService.queryUsernameIsExist(username);
        if(isExist){
            return JSONResult.errorMsg("用户名已存在！");
        }

        return JSONResult.ok();
    }

    @ApiOperation(value = "用户注册",notes = "用户注册",httpMethod = "POST")
    @PostMapping("/regist")
    public JSONResult regist(@RequestBody UserBO userBO,
                             HttpServletRequest request,
                             HttpServletResponse response){
        // 0. 一切前端验证都不要相信
        String username = userBO.getUsername();
        String password = userBO.getPassword();
        String confirmPwd = userBO.getConfirmPassword();

        // 1. 判断用户名密码不能为空
        if(StringUtils.isBlank(username) ||
                StringUtils.isBlank(password) ||
                StringUtils.isBlank(confirmPwd) ){

            return  JSONResult.errorMsg("用户名或密码不能为空");
        }
        // 2. 查询用户名是否存在
        boolean isExist = userService.queryUsernameIsExist(username);
        if(isExist){
            return  JSONResult.errorMsg("用户名已存在");
        }
        // 3. 密码长度不能少于6位
        if(password.length() < 6){
            return  JSONResult.errorMsg("密码长度不能少于6位");

        }

        // 4. 判断两次密码是否一致
        if(!password.equals(confirmPwd)){
            return  JSONResult.errorMsg("两次输入的密码不一致");
        }

        // 5. 实现注册
        User userResult = userService.createUser(userBO);
        userResult = setNullProperty(userResult);
        CookieUtils.setCookie(request, response, "user",JsonUtils.objectToJson(userResult), true);


        return JSONResult.ok();
    }

    @ApiOperation(value = "用户登录",notes = "用户登录",httpMethod = "POST")
    @PostMapping("/login")
    public JSONResult login(@RequestBody UserBO userBO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 0. 一切前端验证都不要相信
        String username = userBO.getUsername();
        String password = userBO.getPassword();


        // 1. 判断用户名密码不能为空
        if(StringUtils.isBlank(username) ||
                StringUtils.isBlank(password)){

            return  JSONResult.errorMsg("用户名或密码不能为空");
        }

        // 2. 查询
        User userResult = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));

        if(userResult == null){
            return JSONResult.errorMsg("用户名或密码不正确");
        }

        userResult = setNullProperty(userResult);
        CookieUtils.setCookie(request, response, "user",JsonUtils.objectToJson(userResult), true);

        // TODO 生成用户token，存入redis会话
        // TODO 同步购物车数据

        return JSONResult.ok(userResult);
    }

    @ApiOperation(value = "退出登录",notes = "用户退出登录",httpMethod = "POST")
    @PostMapping("/logout")
    public JSONResult logout(@RequestBody UserBO userBO, HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 清除用户的相关cookie
        CookieUtils.deleteCookie(request, response, "user");

        return JSONResult.ok();
    }


    /**
     * 敏感数据置空
     * @return
     */
    private User setNullProperty(User userResult){
        userResult.setPassword(null);
        userResult.setMobile(null);
        userResult.setEmail(null);
        userResult.setCreatedTime(null);
        userResult.setUpdatedTime(null);
        userResult.setBirthday(null);

        return  userResult;
    }


}
